package com.game.doudizhu.core;

import com.game.doudizhu.model.*;
import com.game.doudizhu.util.CardPatternUtil;

import java.util.*;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AIGameSimulator {
    private static final Logger logger = LoggerFactory.getLogger(AIGameSimulator.class);
    
    public static void main(String[] args) {
        // 创建三个AI玩家
        AIPlayer player1 = AIPlayer.createAIPlayer("AI玩家1");
        AIPlayer player2 = AIPlayer.createAIPlayer("AI玩家2");
        AIPlayer player3 = AIPlayer.createAIPlayer("AI玩家3");
        player1.setId(1L);
        player2.setId(2L);
        player3.setId(3L);
        
        // 初始化游戏状态
        GameState gameState = new GameState();
        gameState.setRoomId(1L);
        gameState.setPlaying(false);
        gameState.setBidding(true);
        
        // 初始化牌组
        List<Card> allCards = GameUtil.initializeCards();
        Collections.shuffle(allCards);
        
        // 发牌
        Map<Long, List<Card>> playerCards = new HashMap<>();
        playerCards.put(1L, new ArrayList<>(allCards.subList(0, 17)));
        playerCards.put(2L, new ArrayList<>(allCards.subList(17, 34)));
        playerCards.put(3L, new ArrayList<>(allCards.subList(34, 51)));
        List<Card> landlordCards = new ArrayList<>(allCards.subList(51, 54));
        
        gameState.setPlayerCards(playerCards);
        gameState.setLandlordCards(landlordCards);
        
        // 叫分阶段
        logger.info("=== 叫分阶段开始 ===");
        int maxBid = 0;
        Long landlordId = null;
        
        for (AIPlayer player : Arrays.asList(player1, player2, player3)) {
            List<Card> cards = playerCards.get(player.getId());
            int bid = AIStrategy.decideBid(cards, maxBid);
            logger.info("玩家 {} 叫分: {}", player.getUsername(), bid);
            
            if (bid > maxBid) {
                maxBid = bid;
                landlordId = player.getId();
            }
            
            if (bid == 3) break;
        }
        
        if (landlordId == null) {
            logger.info("没有人叫分，游戏重新开始");
            return;
        }
        
        // 确定地主
        logger.info("玩家 {} 成为地主，叫分: {}", landlordId, maxBid);
        gameState.setLandlordId(landlordId);
        playerCards.get(landlordId).addAll(landlordCards);
        
        // 添加以下代码来展示牌
        logger.info("\n=== 各玩家手牌 ===");
        for (AIPlayer player : Arrays.asList(player1, player2, player3)) {
            List<Card> cards = playerCards.get(player.getId());
            // 按照点数排序
            cards.sort((a, b) -> b.getWeight() - a.getWeight());
            
            String role = player.getId().equals(landlordId) ? "地主" : "农民";
            logger.info("{}({}) 的牌: {}", 
                player.getUsername(), 
                role,
                cards.stream()
                    .map(card -> {
                        String suitSymbol = "";
                        switch (card.getSuit()) {
                            case HEARTS: suitSymbol = "♥"; break;
                            case DIAMONDS: suitSymbol = "♦"; break;
                            case CLUBS: suitSymbol = "♣"; break;
                            case SPADES: suitSymbol = "♠"; break;
                            case JOKER: suitSymbol = ""; break;
                        }
                        if (card.getSuit() == Card.Suit.JOKER) {
                            return card.getRank().equals("BIG") ? "大王" : "小王";
                        }
                        return suitSymbol + card.getRank();
                    })
                    .collect(Collectors.joining(" "))
            );
        }
        
        logger.info("底牌: {}", 
            landlordCards.stream()
                .map(card -> {
                    String suitSymbol = "";
                    switch (card.getSuit()) {
                        case HEARTS: suitSymbol = "♥"; break;
                        case DIAMONDS: suitSymbol = "♦"; break;
                        case CLUBS: suitSymbol = "♣"; break;
                        case SPADES: suitSymbol = "♠"; break;
                        case JOKER: suitSymbol = ""; break;
                    }
                    if (card.getSuit() == Card.Suit.JOKER) {
                        return card.getRank().equals("BIG") ? "大王" : "小王";
                    }
                    return suitSymbol + card.getRank();
                })
                .collect(Collectors.joining(" "))
        );
        
        // 开始游戏
        gameState.setBidding(false);
        gameState.setPlaying(true);
        gameState.setCurrentPlayerId(landlordId);
        
        // 游戏主循环
        logger.info("=== 游戏开始 ===");
        List<Card> lastPlayedCards = null;
        Long lastPlayerId = null;
        int passCount = 0;
        
        while (true) {
            Long currentPlayerId = gameState.getCurrentPlayerId();
            List<Card> currentPlayerCards = playerCards.get(currentPlayerId);
            boolean isLandlord = currentPlayerId.equals(landlordId);
            
            // 展示当前玩家的手牌
            currentPlayerCards.sort((a, b) -> b.getWeight() - a.getWeight());
            logger.info("\n当前玩家 {} ({}) 的手牌: {}", 
                currentPlayerId, 
                isLandlord ? "地主" : "农民",
                currentPlayerCards.stream()
                    .map(card -> {
                        String suitSymbol = "";
                        switch (card.getSuit()) {
                            case HEARTS: suitSymbol = "♥"; break;
                            case DIAMONDS: suitSymbol = "♦"; break;
                            case CLUBS: suitSymbol = "♣"; break;
                            case SPADES: suitSymbol = "♠"; break;
                            case JOKER: suitSymbol = ""; break;
                        }
                        if (card.getSuit() == Card.Suit.JOKER) {
                            return card.getRank().equals("BIG") ? "大王" : "小王";
                        }
                        return suitSymbol + card.getRank();
                    })
                    .collect(Collectors.joining(" "))
            );
            
            if (lastPlayedCards != null) {
                logger.info("上家出牌: {}", 
                    lastPlayedCards.stream()
                        .map(card -> {
                            String suitSymbol = "";
                            switch (card.getSuit()) {
                                case HEARTS: suitSymbol = "♥"; break;
                                case DIAMONDS: suitSymbol = "♦"; break;
                                case CLUBS: suitSymbol = "♣"; break;
                                case SPADES: suitSymbol = "♠"; break;
                                case JOKER: suitSymbol = ""; break;
                            }
                            if (card.getSuit() == Card.Suit.JOKER) {
                                return card.getRank().equals("BIG") ? "大王" : "小王";
                            }
                            return suitSymbol + card.getRank();
                        })
                        .collect(Collectors.joining(" "))
                );
            }
            
            // AI出牌
            List<Card> cardsToPlay = AIStrategy.decideCards(
                currentPlayerCards,
                lastPlayedCards,
                isLandlord,
                gameState
            );
            
            if (cardsToPlay.isEmpty()) {
                logger.info("玩家 {} 选择不要", currentPlayerId);
                passCount++;
                if (passCount == 2 && lastPlayedCards != null) {
                    lastPlayedCards = null;
                    passCount = 0;
                }
            } else {
                logger.info("玩家 {} 出牌: {}", currentPlayerId, 
                    cardsToPlay.stream()
                        .map(card -> {
                            String suitSymbol = "";
                            switch (card.getSuit()) {
                                case HEARTS: suitSymbol = "♥"; break;
                                case DIAMONDS: suitSymbol = "♦"; break;
                                case CLUBS: suitSymbol = "♣"; break;
                                case SPADES: suitSymbol = "♠"; break;
                                case JOKER: suitSymbol = ""; break;
                            }
                            if (card.getSuit() == Card.Suit.JOKER) {
                                return card.getRank().equals("BIG") ? "大王" : "小王";
                            }
                            return suitSymbol + card.getRank();
                        })
                        .collect(Collectors.joining(" "))
                );
                lastPlayedCards = cardsToPlay;
                lastPlayerId = currentPlayerId;
                gameState.setLastPlayerId(lastPlayerId);
                passCount = 0;
                
                // 移除出掉的牌
                currentPlayerCards.removeAll(cardsToPlay);
                
                // 检查是否获胜
                if (currentPlayerCards.isEmpty()) {
                    logger.info("=== 游戏结束 ===");
                    logger.info("玩家 {} {}胜利!", currentPlayerId, 
                        isLandlord ? "（地主）" : "（农民）");
                    return;
                }
            }
            
            // 移动到下一个玩家
            List<Long> playerIds = new ArrayList<>(playerCards.keySet());
            int currentIndex = playerIds.indexOf(currentPlayerId);
            int nextIndex = (currentIndex + 1) % playerIds.size();
            gameState.setCurrentPlayerId(playerIds.get(nextIndex));
        }
    }


} 